#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版AI童话书应用
用于演示基本功能
"""

import os
import json
import random
from datetime import datetime

try:
    from flask import Flask, render_template, request, jsonify
    FLASK_AVAILABLE = True
except ImportError:
    FLASK_AVAILABLE = False
    print("Flask未安装，将使用命令行模式演示")

# 简单的故事模板
STORY_TEMPLATES = [
    {
        "title": "魔法森林的冒险",
        "beginning": "在一个神秘的魔法森林里，住着一只聪明的小{animal}。有一天，{animal}发现了一个闪闪发光的{object}...",
        "choices": [
            {"text": "拿起这个神奇的物品", "next": "pickup"},
            {"text": "小心地观察周围", "next": "observe"},
            {"text": "寻找其他动物朋友", "next": "friends"}
        ]
    },
    {
        "title": "海底世界探险",
        "beginning": "在深蓝色的海底，小{animal}游过了美丽的珊瑚礁。突然，{animal}看到了一座神秘的{object}...",
        "choices": [
            {"text": "游向神秘的建筑", "next": "explore"},
            {"text": "和海洋朋友们商量", "next": "discuss"},
            {"text": "寻找宝藏线索", "next": "treasure"}
        ]
    }
]

STORY_CONTINUATIONS = {
    "pickup": "当{animal}触碰到{object}时，突然间整个森林都亮了起来！原来这是一个魔法{object}，它能够...",
    "observe": "{animal}仔细观察后发现，这个{object}周围有很多小脚印，看起来其他小动物也来过这里...",
    "friends": "{animal}呼唤朋友们，很快小兔子、小松鼠都跑了过来，大家一起看着这个神奇的{object}...",
    "explore": "{animal}勇敢地游向{object}，发现这是一座古老的海底宫殿，里面传来美妙的音乐声...",
    "discuss": "海豚朋友告诉{animal}，这座{object}里住着善良的海洋精灵，她会帮助迷路的小动物...",
    "treasure": "{animal}在{object}附近发现了一张古老的藏宝图，上面画着通往神秘宝藏的路线..."
}

class SimpleFairyTaleGenerator:
    def __init__(self):
        self.animals = ["小兔子", "小狐狸", "小熊", "小鹿", "小松鼠", "小猫咪"]
        self.objects = ["水晶球", "魔法书", "宝石", "古堡", "花园", "小屋"]
        
    def generate_story(self, template_id=None, animal=None, obj=None):
        """生成故事"""
        if template_id is None:
            template_id = random.randint(0, len(STORY_TEMPLATES) - 1)
        
        template = STORY_TEMPLATES[template_id]
        
        if animal is None:
            animal = random.choice(self.animals)
        if obj is None:
            obj = random.choice(self.objects)
            
        story = {
            "title": template["title"],
            "content": template["beginning"].format(animal=animal, object=obj),
            "choices": template["choices"],
            "characters": {"animal": animal, "object": obj},
            "template_id": template_id
        }
        
        return story
    
    def continue_story(self, choice_id, animal, obj):
        """继续故事"""
        if choice_id in STORY_CONTINUATIONS:
            continuation = STORY_CONTINUATIONS[choice_id].format(animal=animal, object=obj)
            
            # 生成新的选择
            new_choices = [
                {"text": "继续探索", "next": "continue"},
                {"text": "寻求帮助", "next": "help"},
                {"text": "回到开始的地方", "next": "return"}
            ]
            
            return {
                "content": continuation,
                "choices": new_choices,
                "is_continuation": True
            }
        else:
            return {"content": "故事还在继续...", "choices": [], "is_continuation": True}

# Flask应用部分
if FLASK_AVAILABLE:
    app = Flask(__name__)
    app.secret_key = 'fairy_tale_secret_key'
    generator = SimpleFairyTaleGenerator()

    @app.route('/')
    def index():
        """主页"""
        return render_template('index.html')

    @app.route('/api/generate_story', methods=['POST'])
    def api_generate_story():
        """生成新故事API"""
        data = request.get_json() or {}
        animal = data.get('animal')
        obj = data.get('object')
        template_id = data.get('template_id')
        
        story = generator.generate_story(template_id, animal, obj)
        return jsonify(story)

    @app.route('/api/continue_story', methods=['POST'])
    def api_continue_story():
        """继续故事API"""
        data = request.get_json() or {}
        choice_id = data.get('choice_id')
        animal = data.get('animal')
        obj = data.get('object')
        
        continuation = generator.continue_story(choice_id, animal, obj)
        return jsonify(continuation)

    @app.route('/api/get_templates', methods=['GET'])
    def api_get_templates():
        """获取故事模板"""
        templates = [{"id": i, "title": t["title"]} for i, t in enumerate(STORY_TEMPLATES)]
        return jsonify(templates)

def demo_command_line():
    """命令行演示模式"""
    print("=" * 50)
    print("🧚‍♀️ AI童话书演示 - 命令行模式")
    print("=" * 50)
    
    generator = SimpleFairyTaleGenerator()
    
    while True:
        print("\n📚 选择操作:")
        print("1. 生成新故事")
        print("2. 查看故事模板")
        print("3. 退出")
        
        choice = input("\n请输入选择 (1-3): ").strip()
        
        if choice == '1':
            print("\n🎭 生成新故事...")
            story = generator.generate_story()
            
            print(f"\n📖 {story['title']}")
            print("-" * 30)
            print(story['content'])
            
            print("\n🔀 你的选择:")
            for i, choice_option in enumerate(story['choices'], 1):
                print(f"{i}. {choice_option['text']}")
            
            user_choice = input("\n请选择 (1-3): ").strip()
            if user_choice.isdigit() and 1 <= int(user_choice) <= len(story['choices']):
                choice_id = story['choices'][int(user_choice) - 1]['next']
                continuation = generator.continue_story(
                    choice_id, 
                    story['characters']['animal'], 
                    story['characters']['object']
                )
                print(f"\n📝 故事继续...")
                print(continuation['content'])
                
        elif choice == '2':
            print("\n📋 可用故事模板:")
            for i, template in enumerate(STORY_TEMPLATES, 1):
                print(f"{i}. {template['title']}")
                
        elif choice == '3':
            print("\n👋 谢谢使用AI童话书！")
            break
        else:
            print("\n❌ 无效选择，请重试")

if __name__ == '__main__':
    if FLASK_AVAILABLE:
        print("🚀 启动AI童话书Web应用...")
        print("📱 访问地址: http://localhost:5000")
        print("🛑 按 Ctrl+C 停止服务")
        try:
            app.run(debug=True, host='0.0.0.0', port=5000)
        except KeyboardInterrupt:
            print("\n👋 应用已停止")
    else:
        demo_command_line()